import { defineStore } from 'pinia';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null,
        verificationCode: '',
        codeSent: false,
        countdown: 0,
        timer: null
    }),
    actions: {
        // 模拟发送验证码
        sendVerificationCode(email) {
            if (this.countdown > 0) return;

            // 生成随机6位验证码
            this.verificationCode = Math.floor(100000 + Math.random() * 900000).toString();
            this.codeSent = true;
            this.countdown = 60;

            // 模拟发送到邮箱 (实际项目中这里应该是API调用)
            console.log(`验证码已发送至 ${email}: ${this.verificationCode}`);

            // 倒计时
            this.timer = setInterval(() => {
                this.countdown--;
                if (this.countdown <= 0) {
                    clearInterval(this.timer);
                }
            }, 1000);
        },
        // 检查邮箱是否已注册
        isEmailRegistered(email) {
            return this.user && this.user.email === email;
        },
        // 注册用户
        registerUser(userData) {
            this.user = userData;
            return Promise.resolve({ success: true });
        },

        // 登录
        login(credentials) {
            if (this.user && this.user.email === credentials.email && this.user.password === credentials.password) {
                return Promise.resolve({ success: true });
            }
            return Promise.resolve({ success: false, message: '邮箱或密码错误' });
        },

        //验证用户输入的验证码是否正确，并且检查邮箱是否与已注册用户的邮箱匹配
        loginWithCode(credentials) {
            if (this.codeSent && this.verificationCode === credentials.code) {
                // 验证码验证通过后的逻辑
                if (!this.isEmailRegistered(credentials.email)) {
                    // 邮箱未注册，直接后台注册
                    this.registerUser({ email: credentials.email });
                }
                return Promise.resolve({ success: true });
            }
            return Promise.resolve({ success: false, message: '验证码错误' });
        },

        // 重置密码
        resetPassword(email, newPassword) {
            if (this.user && this.user.email === email) {
                this.user.password = newPassword;
                return Promise.resolve({ success: true });
            }
            return Promise.resolve({ success: false, message: '邮箱未注册' });
        },

        // 添加 setPassword 方法，邮箱加验证码登录后的密码放置
        setPassword({ email, password }) {
            if (this.user && this.user.email === email) {
                this.user.password = password;
                return Promise.resolve({ success: true });
            }
            return Promise.resolve({ success: false, message: '用户未登录' });
        }
    }
});